//
//  WNReadVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/13.
//

import UIKit
import Lottie
import RyukieSwifty

class WNReadVC: WNBaseVC {
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.removeObserver(self, name: WNNotiName.collectNoti, object: nil)
        NotificationCenter.default.removeObserver(self, name: WNNotiName.loginNoti, object: nil)
        NotificationCenter.default.removeObserver(self, name: WNNotiName.rechargeNoti, object: nil)
        READ_RECORD_CURRENT_CHAPTER_LOCATION = 0
        clearVC()
        stopReadTimer()
        stopLimitedTimer()
        navView.isBegin = false
        navView.isPlay = false
        WNReadManager.shared.stopReading()
        audioAnimation()
    }
    
    lazy var readView: UIView = {
        let view = UIView()
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(hiddenView))
        tap.numberOfTapsRequired = 1
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var readBomView: ReadBomView = {
        let view = ReadBomView()
        return view
    }()
    
    lazy var colBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.imageView?.contentMode = .scaleAspectFit
        btn.rx.tap.bind { [weak self] in
            self?.collectRequest()
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
    
    lazy var rechargeBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.rx.tap.bind { [weak self] in
            if let m = self?.limitedModel {
                showSpringType(.readingLimited)
                WNSpringView.shared.limitedModel = m
                WNSpringView.shared.isRightClosure = { isRight in
                    if isRight {
                        WNBuriedManager.shared.logProductItem(m.productId ?? "", m.productName ?? "", m.price)
                        WNLimitedPayManager.shared.creatLimitedRechargeOrder(m.productId ?? "", m.productName ?? "", m.productIds ?? "", m.price)
                    }
                }
            }
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()

    lazy var readSettingView: ReadSettingView = {
        let view = ReadSettingView()
        view.fontView.changeFontClosure = { [weak self] updateFont in
            self?.darkModeConfig(updateFont)
        }
        view.flipView.changeFlipClosure = { [weak self] in
            self?.darkModeConfig()
        }
        return view
    }()
    
    lazy var readLockView: ReadLockView = {
        let view = ReadLockView()
        view.btnClosure = { [weak self] str in
            self?.handleBuyChapter(str)
        }
        view.isHidden = true
        return view
    }()

    lazy var animationView: LottieAnimationView = {
        var view = LottieAnimationView()
        let animation = LottieAnimation.named("unlock")
        view.animation = animation
        view.animationSpeed = 1.75
        view.shouldRasterizeWhenIdle = true
        view.isHidden = true
        return view
    }()
    
    /// 垂直滚动
    var scrollVC: WNReadScrollVC?
    /// 仿真
    var pageVC: UIPageViewController?
    /// 覆盖
    var coverVC: SNCoverVC?

    var currentReadVC: WNCurrentReadVC?
            
    var bookDetailModel: BookDetailModel? {
        didSet {
            readLockView.bookDetailModel = bookDetailModel
            colBtn.isSelected = bookDetailModel?.favorite ?? false
        }
    }
    
    var chapterArr = [ChapterDetailModel]()
    
    var rechargeArr = [RechargeDetailModel]() {
        didSet {
            readLockView.storeView.rechargeArr = rechargeArr
        }
    }
    
    var recArr = [BookDetailModel]()
    
    var recordModel: BookRecordModel?

    var showSetting = false

    var showTopBom = false

    var isTransition = false
        
    var selChapterId = NSNumber(value: 0)

    var tempNumber = 1
    /// 是否章节选择切换过来
    var isSelPage = false
    /// 翻上一页请求获取数据时，需要翻到最后一页
    var isPrevious = false
    
    var jumpChapterId = ""

    // 阅读时间timer监测
    var readTimer: Timer?

    var readTime = 0
    
    var todayReadTime = 0
    
    var activeTaskModel: TaskModel?

    var taskModel: TaskModel?
    
    // 限时充值timer监测
    var limitedTimer: Timer?

    var limitedTime = 0

    var limitedArr = [RechargeDetailModel]()
    
    var limitedModel: RechargeDetailModel? {
        didSet {
            if limitedModel == nil {
                rechargeBtn.isHidden = true
            }
            limitedModel == nil ? stopLimitedTimer() : startLimitedTimer()
            limitedAnimation()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getUserGold { [weak self] _ in
            self?.readLockView.darkModeConfig()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        UIApplication.shared.isIdleTimerDisabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UIApplication.shared.isIdleTimerDisabled = false
    }
    
    override func loadView() {
        view = ScreenShieldView.create()
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        saveReadConfigItem("brightness", Float(UIScreen.main.brightness))
    }
    
    override func viewConfig() {
        navView.frame = CGRect(x: 0, y: -NaviTotalHeight, width: ScreenW, height: NaviTotalHeight)
        view.addSubview(readView)
        view.addSubview(readBomView)
        view.addSubview(colBtn)
        view.addSubview(rechargeBtn)
        view.addSubview(readSettingView)
        view.addSubview(readLockView)
        view.addSubview(animationView)
        readView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        readBomView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(TabBarMargin+84)
            make.height.equalTo(TabBarMargin+84)
        }
        colBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.bottom.equalTo(-TabBarMargin-84-24)
            make.width.height.equalTo(48)
        }
        rechargeBtn.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.bottom.equalTo(colBtn.snp.top).offset(-24)
            make.width.height.equalTo(48)
        }
        readSettingView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(TabBarMargin+325)
            make.height.equalTo(TabBarMargin+325)
        }
        readLockView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        animationView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(160)
            make.height.equalTo(160)
        }
        view.bringSubviewToFront(navView)
    }
        
    override func dataConfig() {
        pageName = "Reading"
        WNBuriedManager.shared.readStart(bookDetailModel?.bookId ?? "")
        if SNKeyedArchiver.isExist(bookDetailModel?.bookId ?? "", READ_RECORD) {
            recordModel = SNKeyedArchiver.unarchiver(bookDetailModel?.bookId ?? "", READ_RECORD) as? BookRecordModel
            recordModel?.updateFont()
        }else {
            recordModel = BookRecordModel()
            recordModel?.bookId = bookDetailModel?.bookId ?? ""
        }
        getChapterListRequest(true)
        readBomView.btnClosure = { [weak self] str in
            if self!.animationView.isAnimationPlaying {
                return
            }
            switch str {
            case "chapter":
                self?.showChapterListVC()
            case "setting":
                self?.handleSetting()
            case "dark":
                self?.setDarkMode()
            case "comment":
                self?.gotoCommentVC()
            default: break
            }
        }
        navView.leftClosure = { [weak self] in
            self?.handleBack()
        }
        navView.rightBtnImge = "book_gift"
        navView.rightClosure = { [weak self] in
            showSpringType(.readingReward, showStr1: "\(self?.taskModel?.gold ?? 0)")
            WNSpringView.shared.isRightClosure = { isRight in
                self?.taskRequest(self?.taskModel?.taskId ?? 0, self?.taskModel?.gold ?? 0)
            }
        }
        navView.ishiddRightBtn = true
        // TODO: - ⚠️：文字转语音
        /*
        navView.audioBtn.isHidden = false
        navView.audioClosure = { [weak self] in
            if self!.navView.isBegin {
                if self!.navView.isPlay {
                    self?.navView.isPlay = false
                    WNReadManager.shared.pauseReading()
                }else {
                    self?.navView.isPlay = true
                    WNReadManager.shared.resumeReading()
                }
                self?.audioAnimation()
            }else {
                let str = (self?.recordModel?.chapterModel?.content ?? "").wn_subString(NSRange.init(location: self?.recordModel?.chapterModel?.location.intValue ?? 0, length: (self?.recordModel?.chapterModel?.content ?? "").count-(self?.recordModel?.chapterModel?.location.intValue ?? 0)))
                WNReadManager.shared.beginReading(str)
                self?.navView.isBegin = true
                self?.navView.isPlay = true
                self?.navView.audioBtn.wn_beginRotation(3)
            }
        }
        WNReadManager.shared.readClosure = { [weak self] isFinish in
        }
         */
    }
    
    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.collectNoti, object: nil, queue: nil) { [weak self] not in
            if let favorite = not.userInfo?["favorite"] as? Bool, let bookId = not.userInfo?["bookId"] as? String {
                if bookId == self?.bookDetailModel?.bookId {
                    self?.bookDetailModel?.favorite = favorite
                }
            }
        }
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.getUserGold({ _ in
                self?.readLockView.darkModeConfig()
            })
            self?.getBookRequest()
        }
        NotificationCenter.default.addObserver(forName: WNNotiName.rechargeNoti, object: nil, queue: nil) { [weak self] not in
            self?.getUserGold({ _ in
                self?.readLockView.darkModeConfig()
            })
            self?.getRechargeList()
            self?.getLimitedRequest()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(brightnessChange), name:UIScreen.brightnessDidChangeNotification, object: nil)
    }
    
    @objc func brightnessChange() {
        let brightness = Float(UIScreen.main.brightness)
        saveReadConfigItem("brightness", brightness)
        readSettingView.brightnessView.slider.value = brightness
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let point = touches.first?.location(in: view) else { return }
        let np = navView.layer.convert(point, from: view.layer)
        if navView.layer.contains(np) {
            return
        }
        let rp = readBomView.layer.convert(point, from: view.layer)
        if readBomView.layer.contains(rp) {
            return
        }
        let sp = readSettingView.layer.convert(point, from: view.layer)
        if readSettingView.layer.contains(sp) {
            return
        }
    }
}

extension WNReadVC {
    
    @objc func hiddenView() {
        if animationView.isAnimationPlaying {
            return
        }
        if isTransition {
            return
        }
        if !readLockView.isHidden {
            return
        }
        if showSetting {
            handleSetting()
            return
        }
        if scrollVC != nil {
            scrollVC?.readTabView.isScrollEnabled = showTopBom
        }
        if pageVC != nil {
            pageVC?.isPagingEnabled = showTopBom
        }
        showTopBom = !showTopBom
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear]) {
            self.readBomView.transform = CGAffineTransform(translationX: 0, y: self.showTopBom ? -TabBarMargin-84 : 0)
            self.navView.transform = CGAffineTransform(translationX: 0, y: self.showTopBom ? NaviTotalHeight : 0)
        } completion: { (finish) in
            if finish {
                self.colBtn.isHidden = !self.showTopBom
                if self.limitedModel != nil {
                    self.rechargeBtn.isHidden = !self.showTopBom
                }
            }
        }
    }
    
    func showChapterListVC() {
        let chapterVC = WNChapterVC()
        chapterVC.isRead = true
        chapterVC.baseId = bookDetailModel?.bookId ?? ""
        chapterVC.chapterIdClosure = { [weak self] chapterId in
            self?.isSelPage = true
            self?.isPrevious = false
            self?.handleChooseChapter(NSNumber(value: chapterId))
            chapterVC.dismiss(animated: true)
        }
        chapterVC.sheetPosition = .left
        chapterVC.displayPercent = 0.8
        chapterVC.translucentValue = 0.5
        chapterVC.becomeSheet()
        chapterVC.modalPresentationStyle = .overFullScreen
        present(chapterVC, animated: true, completion: nil)
    }

    func handleSetting() {
        showSetting = !showSetting
        let y = showSetting ? -TabBarMargin-325 : 0
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear]) {
            self.readSettingView.transform = CGAffineTransform(translationX: 0, y: y)
        } completion: { (finish) in
            if finish {
            }
        }
    }
    
    func setDarkMode() {
        getDarkMode() == 0 ? saveDarkMode(1) : saveDarkMode(0)
        darkModeConfig()
    }

    func gotoCommentVC() {
        let commentVC = WNCommentVC()
        commentVC.baseId = bookDetailModel?.bookId ?? ""
        navigationController?.pushViewController(commentVC, animated: true)
    }
    
    /// 更换🔆
    func darkModeConfig(_ isUpdateFont: Bool = false) {
        view.backgroundColor = isDark() ? .init(named: "black_121212") : .white
        colBtn.setImage(UIImage(named: isDark() ? "read_collect_night" : "read_collect"), for: .normal)
        rechargeBtn.setImage(UIImage(named: isDark() ? "read_recharge_night" : "read_recharge"), for: .normal)
        colBtn.setImage(UIImage(named: isDark() ? "read_collect_sel_night" : "read_collect_sel"), for: .selected)
        colBtn.wn_cornerWithBorder(0, 0, .white, 1, .init(white: isDark() ? 1 : 0, alpha: 0.1), .zero, 2)
        navView.darkModeConfig()
        readBomView.darkModeConfig()
        readSettingView.darkModeConfig()
        readLockView.darkModeConfig()
        creatPageVC(getCurrentReadVC(isUpdateFont))
    }
    
    func handleBack() {
        if animationView.isAnimationPlaying {
            animationView.stop()
        }
        var item = 0
        for (i, v) in chapterArr.enumerated() {
            if recordModel?.chapterModel?.chapterId == v.chapterId {
                item = i
            }
        }
        if item > ((bookDetailModel?.freepage ?? 0)-1) {
            if item == ((bookDetailModel?.chapters ?? 0)-1) {
                showReadRec(recArr)
            }else {
                if !(bookDetailModel?.favorite ?? true) {
                    showSpringType(.addLibrary)
                    WNSpringView.shared.isRightClosure = { [weak self] isRight in
                        if isRight {
                            self?.collectRequest(true)
                        }else {
                            self?.stopReadTimer()
                        }
                    }
                }else {
                    stopReadTimer()
                }
            }
        }else {
            showReadRec(recArr)
        }
    }
}
